<?php

// +----------------------------------------------------------------------
// | 任务关联服务层
// +----------------------------------------------------------------------
// | 主要服务于合同
// +----------------------------------------------------------------------
// | 错误编码头 245xxx
// +----------------------------------------------------------------------
namespace common\service;


use common\model\TaskModel;
use common\model\TaskRelationModel;
use Exception;
use support\SingletonTrait;

class TaskRelationService
{
    use SingletonTrait;

    /**
     * 获得关联的子级任务
     * @param array $orderTaskIdData
     * @param string $fields
     * @return mixed
     */
    public function getChildrenTask(array $orderTaskIdData, $fields = 'id')
    {
        $model = model(TaskRelationModel::class);
        $relations = $model->where(['source_task_id' => ['IN', implode(',', $orderTaskIdData)]])->field("target_task_id")->select();
        $relations = array_column($relations, 'target_task_id', 'target_task_id');
        return model(TaskModel::class)->where(['id' => ['IN', implode(',', $relations)]])->field($fields)->select();
    }


    /**
     * add task_relation_data 表数据
     * @param int $projectId
     * @param $taskRelationData
     * @return bool
     * @throws Exception
     */
    public function addProjectTaskRelationData(int $projectId, $taskRelationData): bool
    {
        if (empty($projectId) || empty($taskRelationData)) {
            return false;
        }
        // 绑定关联关系
        $suffix = sprintf('_project_%d', $projectId);
        $res = model(TaskRelationModel::class)->setSuffix($suffix)->addItem($taskRelationData);
        if (empty($res)) {
            return false;
        }
        return true;
    }
}